package servlet;

import DAO.OrderDAO;
import bean.Order;
import bean.OrderItem;
import bean.Product;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;
import util.Item;
import util.Page;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class OrderServlet extends BaseBackServlet {
    @Override
    public String add(HttpServletRequest request, HttpServletResponse response, Page page) {
        return null;
    }

    @Override
    public String delete(HttpServletRequest request, HttpServletResponse respone, Page page) {
        return null;
    }

    @Override
    public String edit(HttpServletRequest request, HttpServletResponse response, Page page) {
        return null;
    }

    @Override
    public String update(HttpServletRequest request, HttpServletResponse response, Page page) {
        return null;
    }

    @Override
    public String list(HttpServletRequest request, HttpServletResponse response, Page page) {
        int start = page.getStart();
        int count = page.getCount();
        int total = orderDAO.getTotal();
//        System.out.println(start+"--"+count+"--"+total);
        page.setTotal(total);
        List<Order> orders= orderDAO.list(start,count);
        orderItemDAO.fill(orders);
        request.setAttribute("orders", orders);
        request.setAttribute("page", page);
        return "jsp/admin/listOrder.jsp";
    }

    public String listItem(HttpServletRequest request, HttpServletResponse response, Page page) throws IOException {
        int oid = Integer.parseInt(request.getParameter("id"));
        List<OrderItem> items = orderItemDAO.listByOrder(oid);
//        request.removeAttribute("items");
        List<Item> list = Item.list(items);
//        System.out.println(list);
//        JSONArray jsonArray = JSONArray.fromObject(list);
        String result = JSONSerializer.toJSON(list).toString();
        response.setContentType("text/html;charset=utf-8");
//        response.getWriter().print("%"+result);
//        request.setAttribute("items"+oid,items);
        return "%"+result;
    }

    public String delivery(HttpServletRequest request, HttpServletResponse response, Page page)
    {
//        System.out.println("111");
        int oid = Integer.parseInt(request.getParameter("id"));
//        System.out.println(oid);
        Order order = orderDAO.get(oid);
//        System.out.println(order);
        order.setStatus(OrderDAO.waitConfirm);
        order.setDeliveryDate(new Date());
//        System.out.println(order);
        orderDAO.update(order);
//        System.out.println(order);
        return "@admin_order_list";
    }
}


